package toy.keli.picmap.tools;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapsdkexample.geometry.markercluster.MyItem;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import toy.keli.picmap.BmapActivity;
import toy.keli.picmap.ConfigActivity;
import toy.keli.picmap.R;
import toy.keli.picmap.model.Reflection;
import toy.keli.picmap.model.def;
import toy.keli.picmap.model.system;
import toy.keli.picmap.model.time;
import toy.keli.picmap.util.utilStore;

/**
 * 配置信息
 */
public class Control implements  Iterable<String>, Iterator {
    BmapActivity act;
    public SharedPreferences config;
    public static int locationClick=0;     //定位按钮单击
    public static boolean zoomEnable;      //缩放启用
    public static boolean scaleEnable;     //比例尺
    public static boolean routeEnable;     //路线按钮
    public static boolean hotmapEnable;    //热力图
    public static boolean trmapEnable;     //路况图
    public static boolean stamapEnable;    //卫星图
    public static boolean animationEnable; //启动动画
    public static boolean autoSearchEnable;//自动更新
    public static boolean fullScreenEnable;//全面屏幕
    public static boolean picShowEnable;    //图片展示
    public static boolean taEnable;         //时间开关
    public static boolean searchEnable;     //搜索匡
    public static boolean bmoveEnable;      //按钮移动
    public static int limit=1000;            //限制条数
    public static int taNextTime =2000;         //切换间隔
    public static long[] date=new long[]{0,0,-1};
    public static String key=""; //关键字过滤

    public Control(BmapActivity bmapActivity) {
        act=bmapActivity;
        config=act.getSharedPreferences("config", Activity.MODE_PRIVATE);
        if(config.getAll().size()==0){
            init();
        }
        def c=new def();
        Map<String,?> all=config.getAll();
        for(String key : all.keySet()){
            c.set(key,all.get(key));
            configAll.add(key);
        }
        c.toObject(this);
    }
    public static void setDate(long t0, long t1) {
        date[0]=t0;
        date[1]=t1;
    }
    public static void setDate(long t0, long t1, int tname) {
        date=new long[]{t0,t1,tname};
    }

    public static void setDateType(int dType) {
        date[2]=dType;
    }

    public static String getDateTypeName() {
        String[] map=new String[]{"天","周","月","季","年"};
        return map[(int)date[2]];
    }


    public void resetDateFilter() {
        Control.date = new long[]{0, 0, -1};
        act.getFilter().runByDate();
        dateIndex=-1;
    }

    public void Postion(String butName, int x,int y) {
        String val=String.format("%s,%s",x,y);
        config.edit().putString(butName,val).commit();
    }
    public void Postion(String butName, View v) {
        String val=config.getString(butName,"");
        String[] p = val.split(",");
        if(p[0].length()>0) {
            int left = Integer.parseInt(p[0]);
            int top = Integer.parseInt(p[1]);
            ConstraintLayout.LayoutParams lpFeedback = (ConstraintLayout.LayoutParams)v.getLayoutParams();
            lpFeedback.setMargins(left, top,0,act.mMapView.getHeight()-top-40);
            v.setLayoutParams(lpFeedback);

            v.setLeft(left);
            v.setTop(top);
        }
    }

    void init(){
        Dialog configDialog = new Dialog(act);
        configDialog.setContentView(R.layout.tools_view);
        def bmap=act.getViewsByTagName(configDialog.getWindow().getDecorView(), Button.class);
        SharedPreferences.Editor edit = config.edit();
        edit.putString("intime",String.valueOf(System.currentTimeMillis()));
        Reflection r=new Reflection(this);
        for(def k: bmap) {
            if(k.toString().endsWith("Enable")) {
                Button b=(Button)bmap.get(k).source();
                edit.putBoolean(k.toString(), b.getTextColors().getDefaultColor() ==Color.parseColor("#0000ff"));
            }else
                edit.putString(k.toString(), r.getField(k.toString()).toString());
        }

        edit.commit();
    }
    //定位功能开关
    //下载地图
    //比例尺
    //缩放工具
    //地图图层 （热力图，路况，卫星，附近 ）
    //图片 ， 收藏（字符串，文章，抖音视频，图片，语音，位置，名片，文件），
    void downCity() {
        act.onLocationDo((location) -> {
            OfflineMap ol = new OfflineMap(act, location);
            if (!ol.status) ol.downloadCity(Integer.valueOf(location.getCityCode()));
        });
    }

    void cityList(View v){
        OfflineMap ol = new OfflineMap();
        def citys = ol.cityList();
        citys.set(-1,"更多");
        String[] items = citys.slice(0,7).toStrings();
        act.popupMenu(v,items,-1,(item)->{
            MenuItem m=(MenuItem)item;
            String cityName = m.getTitle().toString();
            if(cityName=="更多"){
                system.msg(act,"待开发");
            }else{
                Show.openCity(cityName);
            }
            act.configDialog.hide();
        });
//        for(def c : citys){
//
//        }
    }

    List<String> configAll=new ArrayList<String>();
    int index=0;
    @Override
    public Iterator<String> iterator() {
        return this;
    }

    @Override
    public boolean hasNext() {
        return index<configAll.size();
    }

    @Override
    public Object next() {
        return configAll.get(index++);
    }

    public boolean get(String k) {
        return config.getBoolean(k,false);
    }

    public void initEvent(def bmap) {
        for(def k : bmap){
            ((View)bmap.get(k).source()).setOnClickListener(new Click());
        }
    }

    public void setIndex(int i) {
        index=i;
    }

    class Click implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            Button b=(Button)v;
            b.getId();
            String key=(String)b.getTag();
            switch (key){
                case "locationClick":    //按钮单击
                    String[] items = new String[]{"目录配置页", "定位功能", "配置弹匡","日期选择"};
                    act.popupMenu(v,items,Control.locationClick,(item)->{
                        MenuItem m=(MenuItem)item;
                        int val= Arrays.asList(items).indexOf(m.getTitle().toString());
                        config.edit().putInt(key,val).commit();
                        Control.locationClick=val;
                    });
                    break;
                case "city":            //地图选择
                    cityList(v);
                    break;
                case "offflineMap":     //离线地图
                    downCity();
                    break;
                case "limit":           //限制条数
                    String[] items2 = new String[]{"100", "1000", "10000","100000"};
                    act.popupMenu(v,items2,Arrays.asList(items2).indexOf(String.valueOf(Control.limit)),(item)->{
                        MenuItem m=(MenuItem)item;
                        int val= Integer.valueOf(m.getTitle().toString());
                        config.edit().putInt(key,val).commit();
                        Control.limit=val;
                    });
                    break;
                case "taNextTime":
                    String[] items0 = new String[]{"0s", "0.2s","0.5s","1s", "2s","5s","10s","30s","60s","150s"};
                    String i=Control.taNextTime>=1000? String.valueOf(Control.taNextTime/1000) : "0."+(Control.taNextTime/100);
                    act.popupMenu(v,items0,Arrays.asList(items0).indexOf(i+"s"),(item)->{
                        MenuItem m=(MenuItem)item;
                        float val= Float.valueOf(m.getTitle().toString().replace("s",""));
                        Control.taNextTime =(int)(val*1000);
                        config.edit().putInt(key,Control.taNextTime).commit();
                    });
                    break;
                case "control":         //管理界面
                    act.startActivity(new Intent(act, ConfigActivity.class));
                    break;
                case "about":           //关于
                    Dialog dlog=act.layoutDialog(R.layout.tools_abaut);
                    TextView button = dlog.findViewById(R.id.permissionButton);
                    TextView text = dlog.findViewById(R.id.permissionText);
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            text.setVisibility(text.getVisibility()==View.GONE ?View.VISIBLE:View.GONE);
                        }
                    });

                    WindowManager.LayoutParams lp = dlog.getWindow().getAttributes();
                    Display display= act.getWindowManager().getDefaultDisplay();
                    lp.width=display.getWidth();
                    dlog.getWindow().setAttributes(lp);
                    dlog.show();
                    //act.configDialog.hide();
                    break;
                case "date":
                    dateFilter(v);
                    break;
                case "taEnable":
                    Show.getTimeAnimation().toggleTaRuning();
                    act.configDialog.hide();
                    break;
                case "bookmark":
                    int[] ids= utilStore.getItemsForInt("bookmark");
                    act.openPics(ids,"free");
                    break;
                default:
                    boolean val=!config.getBoolean(key,false);
                    config.edit().putBoolean(key,val).commit();
                    create(act,act.mMapView,act.mMapView.getMap());
                    b.setTextColor(val ? Color.parseColor("#0000ff") : Color.parseColor("#000000"));
                    if(key.equals("fullScreenEnable") || key.equals("bmoveEnable"))    act.recreate(); //全屏或按钮可移动
                    if(key.equals("picShowEnable"))    act.addMarkers();   //图片显示
            }
        }
    }
    public static void setTaEnable(boolean v, BmapActivity act) {
        Control.taEnable=v;
        if(act==null || Show.getTimeAnimation(false)==null) return;
        act.setmButtonIco(Control.taEnable ? "⏸":"▶️");
    }


    public int dateIndex=-1;
    public static String[] datesMap = new String[]{"day","year","season","mouth","week"};
    public static String getDateType(){
        if(date[2]==-1) return "page";
        return datesMap[(int) date[2]];
    }
    public static String getDateType(int type){
        return datesMap[type];
    }
    //日期选择
    public void dateFilter(View v){
        String[] dates = new String[]{"天","周","月","季","年","日历"};
        Button vv = (Button) v;

        //弹出日期选择菜单
        PopupMenu m = act.popupMenu(v, dates,dateIndex , (item) -> {
            MenuItem mi = ((MenuItem) item);
            String title = mi.getTitle().toString();
            dateIndex=mi.getItemId();
            time t=new time();
            long nt=t.getTime();
            if(title.equals("日历")){
                act.getFilter().selectDay((t0, t1) -> {
                    Control.date = new long[]{t0, t1, 0};
                    List<MyItem> items = act.getFilter().runByDate();
//                    new Show.timeAnimation(items, taNextTime);
                });
                return ;
            }
            //复选作为删除
            if (mi.isChecked()) {
                Control.date = new long[]{0, 0, -1};
                mi.setChecked(false);
                Control.setDateType(-1);
                act.getProgressBar().progresUpdate(-1,0,"");
            }else if(title.equals("天")){
                Control.date = new long[]{t.getTime("yyyy-MM-dd"), t.getTime(), -1};
//                new Show.timeAnimation();
              new Show.timeAnimation(act.getFilter().runByDate(),Control.taNextTime);
            }else{
                Control.setDateType(dateIndex);

               // act.setmButtonIco(Control.getDateTypeName());
                new Show.timeAnimation();
            }
            if (act.configDialog != null) act.configDialog.hide();

        });

    }

    public static Control create(BmapActivity bmapActivity, MapView mMapView, BaiduMap mBaiduMap) {
        Control config=new Control(bmapActivity);

        mMapView.showZoomControls(config.zoomEnable);   //缩放
        mMapView.showScaleControl(config.scaleEnable);    //比例尺
        mBaiduMap.setMapType(config.stamapEnable ? BaiduMap.MAP_TYPE_SATELLITE: BaiduMap.MAP_TYPE_NORMAL); //卫星地图还是正常地图
        mBaiduMap.setBaiduHeatMapEnabled(config.hotmapEnable);        //热力图
        mBaiduMap.setTrafficEnabled(config.trmapEnable);         //路况图
        bmapActivity.setSearchEnabled(config.searchEnable);
        // 解决圆角屏幕手机，地图loggo被遮挡的问题
        //mBaiduMap.setViewPadding(30, 0, 30, 20);

        return config;
    }

    /**
     * 配置页面的展示
     */
    public void show() {
        act.configDialog =act.layoutDialog(R.layout.tools_view);
        //获取所有按钮 循环配置这写按钮的颜色
        def bmap=act.getViewsByTagName(act.configDialog.getWindow().getDecorView(),Button.class);
        for(String k: this){
            if(!k.endsWith("Enable")) continue;
            Button b=(Button)bmap.get(k).source();
            if(b!=null)
                b.setTextColor(this.get(k)  ? Color.parseColor("#0000ff") : Color.parseColor("#000000"));
        }
        this.setIndex(0);
        this.initEvent(bmap);
        act.configDialog.show();
    }


}
